package com.ship.common.core.mybatis.mapping;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.PageBean;
import com.ship.common.core.utils.FieldUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 31463
 */
@Slf4j
public abstract class BaseMapping {

    /**
     * apply
     *
     * @param root         root
     * @param field        field
     * @param queryWrapper query wrapper
     */
    public abstract void apply(Object root, Field field, QueryWrapper<?> queryWrapper);

    protected Object getValue(Object root, Field field) {
        Object value = null;
        try {
            value = FieldUtil.getGetter(field).invoke(root);
        } catch (IllegalAccessException | NoSuchMethodException | SecurityException | InvocationTargetException |
                IllegalArgumentException e) {
            log.error("BaseMapping.getValue", e);
        }
        Class<?> o = field.getType();
        if (value != null && o.isEnum()) {
            try {
                Class<?> clazz = value.getClass();
                for (Field f : clazz.getDeclaredFields()) {
                    if ("code".equals(f.getName())) {
                        return f.get(value).toString();
                    }
                }
            } catch (Exception e) {
                log.error("BaseMapping.getValue", e);
            }
        }
        return value;
    }

    public abstract <T extends PageBean> void applyList(Object root, Field field, QueryWrapper<T> queryWrapper, String keyName);
}
